The Roadmap: Module 03

Hooks: The Functional
Superpowers.

Hooks allow you to use state and other React features without writing a class.
They are the building blocks of modern React architecture.

The Laws of Hooks

1. Call at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions. Hooks must always be called at the top of your React function.

❌ Incorrect if (user) { useEffect(() => { ... }); }
✅ Correct useEffect(() => { if (user) { ... } }, [user]);

2. Only Call from React Functions

Hooks can only be used in Function Components or Custom Hooks. They will not work in regular JavaScript functions.

❌ Regular JS Function function calculateData() { const [val] = useState(0); return val * 2; }
✅ React Component function MyCard() { const [val] = useState(0); return ( <div>{val}</div> ); }
01

useState: The Light Switch

Visual Destructuring

[
isOn
,
setIsOn
] = useState ( false )

The State

Current light status (On/Off).

The Switch

Toggles the light status.

How it works

Think of useState as a light switch on a wall. When you flip the switch (setIsOn), the room changes (re-render) and the light reflects the new state instantly.

const [isOn, setIsOn] = useState(false);

// Calling this function flips the switch
const toggleLight = () => {
  setIsOn(!isOn);
};

Component Memory

Normal Variable

Resets on Re-render

React State

Preserved in Memory

"React remembers, variables forget."
02

useEffect: The Smart Window

Visual Syntax Breakdown

useEffect (
() => { ... }
,
[deps]
)

The Action

Check for rewards or change world.

The Trigger

Run only when your score changes.

Mental Model

Think of `useEffect` as an Auto-Leveler. It sits in the background and waits. Whenever you gain a point, it automatically checks: "Do we need to level up now?"

useEffect(() => {
  // Check for level up
  if (score >= 100) setLevel(2);

  // Cleanup (runs before next update)
  return () => console.log("Cleaning up!");

}, [score]); // Watch ONLY the score

The Component Life Path

The Birth (Mount)

The very first time the component appears. The effect runs once automatically.

The Update (Sync)

Whenever [score] changes, the effect re-runs to keep things in sync.

The Exit (Cleanup)

Before the component leaves, the Return Function runs to stop timers or save data.

03

useRef: The Ghost Variable

Quick Summary

Think of useRef as a memory vault that React doesn't track. It lets you "remember" data without forcing the screen to refresh.

While State handles things the user sees, Ref handles the "behind-the-scenes" logic that doesn't need a UI update.

What you give it

The "Starter" Value

Put anything in the parenthesis useRef(0) to set the starting value. React puts this inside a box for you to use later.

What it gives back

A "Magic Box" Object

It hands you an object that stays exactly the same forever. To see or change the data inside, you just open the .current lid.

The Code View
{
  current: your_data
}

Persistence: The One-Time Setup

A normal variable let x dies every time the component refreshes. A Ref is different:

  • It's created only once on the first load.
  • It survives every re-render (refresh).
  • Changing it is silent (React ignores the change).

01. The Hands-on Tool

"Reach out and touch the HTML."

Use this to grab a specific element (like a search box) to force focus, play a video, or measure how big it is.

<input ref={myRef} />

myRef.current.focus();

02. The Secret Note

"Store info without anyone knowing."

Store data that stays safe during refreshes, but doesn't make the screen flicker or reload when you change it (like a Timer ID).

// Silent update

myRef.current = "Timer_ID_123";

Reference vs State

Feature
useState
useRef
Trigger Re-render?
Yes
No
Persistence
Always
Always
Best for...
Screen Data
Logic/DOM

Basically: State is for things the user sees. Ref is for things the developer needs.

04

useContext: Global Access

Quick Summary

Context makes your data available everywhere. Instead of passing props down manually, any component can reach out and grab what it needs.

1

The Catalog

LibraryContext.jsx

import { createContext } from 'react';


export const LibraryCtx = createContext();

  • Import the createContext tool from React.
  • Create the unique "ID" for your shared library catalog.
2

The Building

LibraryBuilding.jsx

<LibraryCtx.Provider value={books}>

<ReaderRooms />

</LibraryCtx.Provider>

  • Wrap your rooms inside the Provider "Building".
  • Stock the shelves by passing data into the value.

The "Direct Grab" Result

Readers get books directly from the Library building

A
Library
Direct Access
C
Reader
ReaderRoom.jsx

import { useContext } from 'react';

import { LibraryCtx } from './Library';

const myBook = useContext(LibraryCtx);

Final Step: Import the useContext hook and the specific LibraryCtx to grab the data instantly from any room.

Theme

Dark/Light Mode

Auth

User Profile

Cart

Global State

05

Optimization Bay

Quick Summary

Optimization hooks act as a smart memory. They tell React to reuse previous work instead of starting over whenever something changes.

useMemo

Value CACHING

If you have a function that takes a long time to run (like filtering 1,000 items), useMemo saves the final result so you don't do the work twice.

In our code example:

  • Input: The price variable
  • Logic: Calculating the 15% tax
  • Output: The stored tax value

Goal: Calculate Tax only when price changes

const [price, setPrice] = useState(100);

// Result is remembered in "tax"
const tax = useMemo(() => {
return price * 0.15; 
}, [price]);

// Returns the number value directly
return <p>Tax: {tax}</p>;

useCallback

FUNCTION CACHING

Normally, React creates a brand new function on every render. useCallback keeps the exact same function in memory.

In our code example:

  • Input: The id of the item
  • Logic: Logging the "buy" message
  • Output: The stable buy function

Goal: Stop child button from re-rendering

const [id, setId] = useState(1);

// Function instance is remembered in "buy"
const buy = useCallback(() => {
console.log("Buying " + id);
}, [id]);

// Pass the same function to child
return <Button action={buy} />;
💡

When to use?

Don't use these for simple logic. Use useMemo for data that takes >10ms to calculate. Use useCallback when passing functions to components wrapped in React.memo().

Control Center

Hooks Summary Dashboard

useState

Memory Battery

useEffect

Sync Window

useRef

Direct DOM

useContext

Broadcast

useMemo

Cached Value

useCallback

Cached Logic